const Controller = require('egg').Controller

class NoticeController extends Controller {
    async index () {
        const { ctx } = this
        const user = ctx.args[0]

        ctx.service.notice.emit(user._id)
    }

    async HaveRead () {
        const { ctx } = this

        const { _id,userId } = ctx.args[0]
        await ctx.model.Notice.updateOne({ _id },{ see:true })
        ctx.service.notice.emit(userId)
    }

    async Chat () {
        const { ctx,app } = this

        const { send_user,receive_user_id,message,time } = ctx.args[0]

        const id = await app.redis.get(receive_user_id)
        //不在线
        if (!id) {
            await ctx.model.Chat.updateOne(
                { user_id:receive_user_id,send_user_id:send_user._id },
                { $push:{ chatList:{ type:'he',message,time } } },
                { upsert:true }
            )
            return
        }
        ctx.socket.to(id).emit('CHAT',{ message,send_user,time })
    }

    async getChat () {
        const { ctx } = this

        const { _id } = ctx.args[0]
        const docs = await ctx.model.Chat.find({ user_id:_id }).populate({
            path:'send_user_id',
            select:{ avatar:1,nickname:1 }
        })

        ctx.socket.emit('GETCHAT',{ docs })

    }

    async delChat () {
        const { ctx } = this

        const { chat_id } = ctx.args[0]
        await ctx.model.Chat.deleteOne({ _id:chat_id })
    }
}

module.exports = NoticeController
